//@ts-nocheck
import React, { useEffect, useState } from 'react';
import axios from "axios";
import { Button, Toast,ImageViewer } from 'antd-mobile';
import { AddOutline,DeleteOutline } from 'antd-mobile-icons'
import './index.less'
interface IuploaderFile {
    fileText: string;
}
interface IfileList {
    name: string;
    url: string;
}
/**
 * 
 * @param fileText 上传按钮文案 
 * @param fileCount 文件数量 
 * @param initFileData 默认文件数量 
 * @param multiple 文件是否多选
 * @param onChange 文件选择的回调 
 * @returns 
 */
const UploaderFile: React.FC<IuploaderFile> = ({ fileText = '', initFileData=[], fileCount = 1, onChange,multiple=false }) => {
    const myRef: React.LegacyRef<HTMLDivElement> = React.createRef();
    const [fileList, setFileList] = useState<IfileList[]>(initFileData)
    const [visible, setVisible] = useState<boolean>(false)
    const [imgIndex,setImgIndex] = useState<number>(1)
    useEffect(() => {
        onChange(fileList)
    }, [fileList])
    const submitUpload = async (e: { target: { files: any; }; }) => {
        const fileData = new FormData();
        const file = e.target.files;
        if (file.length > fileCount) {
            Toast.show({
                icon: "fail",
                content: `文件数量不能大于${fileCount}个`,
            });
            return false
        } else {
            const uploadImg = (files, formData) => {
                return new Promise((resolve, reject) => {
                    axios.post("/api/seh-resource/attach/uploads", formData, {
                        headers: {
                            "Content-type": "multipart/form-data",
                        },
                    })
                    .then(res => {
                        const { code, data } = res.data;
                        if (code === 200) {
                            resolve({
                                url: data[0]?.link,
                                name: data[0]?.name
                            })
                        } else {
                            Toast.show({
                                icon: "fail",
                                content: "上传失败！",
                            });
                        }
                    })
                    .catch(err => {
                        reject(err)
                        Toast.show({
                            icon: "fail",
                            content: "上传失败！",
                        });
                    })
                })
            }
            const beforeUpload = (files) => {
                const isLt10M = files.size / 1024 / 1024 < 10;
                if (!isLt10M) {
                    Toast.show({
                        icon: "fail",
                        content: "不能超过10M",
                    });
                }
                return isLt10M
            }
            let fileArr = []
            for (var i = 0; i < file.length; i++) {
                if (beforeUpload(file[i])) {
                    fileData.append('file', file[i])
                    fileArr.push(await uploadImg(file[i], fileData))
                    fileData.delete('file')
                } else {
                    Toast.show({
                        icon: "fail",
                        content: "上传失败！",
                    });
                }
            }
            
            Promise.all(fileArr)
                .then((res) => {
                    Toast.show({
                        icon: "success",
                        content: "上传成功",
                    });
                    setFileList((v) => {
                        return [
                            ...v,
                            ...res
                        ].map((item,index)=>{
                            return {
                                ...item,
                                key:index+1
                            }
                        })
                    })
                })
                .catch((error) => {
                    Toast.show({
                        icon: "fail",
                        content: "上传失败！",
                    });
                })
        }
    }
    const onDelete = (index:number)=>{
        const list = [...fileList];
        list.splice(index,1)
        setFileList(list)
    }
    const openImg = (index: number)=>{
        setImgIndex(index)
        setVisible(true)
    }
    return <>
        <div className='uploaderFile'>
            {
                fileList.map((item, index) => {
                    return <div className='file_list' key={item.key}>
                        <img src={item.url} alt="" className='img' onClick={()=>openImg(index)} />
                        <div className='delete_box' onClick={()=>onDelete(index)}>
                            <DeleteOutline />
                        </div>
                    </div>
                })
            }
            {
                fileList.length < fileCount ?
                    <div className='file_list uploader_box'>
                        <Button type='text'>{fileText || <AddOutline />}</Button>
                        <input type="file" ref={myRef} onChange={submitUpload} multiple={multiple} />
                    </div> : null
            }
        </div>
        <ImageViewer.Multi
            classNames={{
                mask: 'customize-mask',
                body: 'customize-body',
            }}
            defaultIndex={imgIndex}
            images={fileList.map(({url})=>url)}
            visible={visible}
            onClose={() => {
                setVisible(false)
            }}
        />
    </>
}
export default UploaderFile